//
//  EditDataVC.m
//  MZJ
//
//  Created by XDD on 16/6/4.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "EditDataVC.h"
#import "EditDataCell.h"

@interface EditDataVC () <UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate> {
    NSArray *nameArr;
    NSString *sex_Str;
    NSString *volunteers_Str;
    NSString *sss;
    UIImage *_faceImage;
    UIImagePickerController *_imagePickerController; /**< 相册选择器 */
}

@property (nonatomic, strong) UITableView *editData_TabelView;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) NSMutableDictionary *dataEdit_dic;
@property (nonatomic, strong) UIImageView *headImageView;

@end

@implementation EditDataVC

- (void)dealloc {

    NSLog(@"editDataVc dealloc");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"完善资料";
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    self.editData_TabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55)];
    self.editData_TabelView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    self.editData_TabelView.delegate = self;
    self.editData_TabelView.dataSource = self;
    [self.editData_TabelView registerNib:[UINib nibWithNibName:@"EditDataCell" bundle:nil] forCellReuseIdentifier:@"editDataCell"];
    self.editData_TabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.editData_TabelView];
    
    // 初始化相册选择器
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    
    if (!_model) {
        _model = [[NetWorkingSModel alloc] init];
    }
    nameArr = @[@"昵称",@"性别",@"年龄",@"真实姓名",@"身份证号码",@"联系方式",@"地址",@"愿意成为志愿者"];
    self.dataEdit_dic = [NSMutableDictionary dictionary];
}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        return 70;
    }
    return 46;
}

//Header的高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 70;
    }
    if (section == 2) {
        return 120*XJVerticalMultiplier();
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *head = [[UIView alloc]init];

    if (section == 0) {
        
        head.frame = CGRectMake(0, 0, kWidth, 70);
        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        UILabel *headLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 25, 95, 20)];
        headLabel.text = @"头像";
        headLabel.font = [UIFont systemFontOfSize:13];
        headLabel.backgroundColor = [UIColor redColor];
        headLabel.textColor = [UIColor blackColor];
        [head addSubview:headLabel];
        
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(115, 10, 50, 50)];
        _headImageView.layer.cornerRadius = 25.0;
        _headImageView.layer.masksToBounds = YES;
        [_headImageView sd_setImageWithURL:[NSURL URLWithString:[DataModel object].userDetail[@"uheadimg"]]
                              placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

        _headImageView.backgroundColor = [UIColor purpleColor];
        [head addSubview:_headImageView];
        
        UIButton *headImageV_Btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        headImageV_Btn.backgroundColor = [UIColor clearColor];
        headImageV_Btn.frame = CGRectMake(10, 10, kWidth - 20, 50);
        [headImageV_Btn addTarget:self action:@selector(headImageV_BtnAction) forControlEvents:UIControlEventTouchUpInside];
        [head addSubview:headImageV_Btn];
        
        return head;
    }
    
    if (section == 2) {
       
        head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 120), NO);
        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        UIButton *quedingBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [quedingBtn setTitle:@"确  定" forState:UIControlStateNormal];
        quedingBtn.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
        [quedingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        quedingBtn.frame = XJFlexibleFrame(CGRectMake(70, 50, 180, 30), NO);
        quedingBtn.layer.cornerRadius = 3.0;
        quedingBtn.layer.masksToBounds = YES;
        [quedingBtn addTarget:self action:@selector(quedingBtnAction) forControlEvents:UIControlEventTouchUpInside];
        quedingBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [head addSubview:quedingBtn];
        
        return head;
    }

    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return nameArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"editDataCell";
    EditDataCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!cell) {
        
        cell = [[EditDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    __weak typeof (self)weakSelf = self;

    cell.chooseImageView.hidden = YES;
    cell.chooseImageView1.hidden = YES;
    cell.chooseLabel.hidden = YES;
    cell.chooseLabel1.hidden = YES;
    cell.chooseBtn.hidden = YES;
    cell.chooseBtn1.hidden = YES;
    cell.nameLabel.text = nameArr[indexPath.row];
//    if (indexPath.row == 0) {
//        cell.editDataTextField.hidden = YES;
//        cell.lineView.hidden = YES;
//        cell.edit_imageView.hidden = YES;
//    }
    if (indexPath.row == 0) {
        cell.editDataTextField.text = [DataModel object].userDetail[@"unickname"];
        cell.editDataTextField.placeholder = @"请输入昵称...";
        cell.editDataTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    if (indexPath.row == 1) {
        cell.editDataTextField.hidden = YES;
        cell.lineView.hidden = YES;
        cell.chooseImageView.hidden = NO;
        cell.chooseImageView1.hidden = NO;
        cell.chooseLabel.hidden = NO;
        cell.chooseLabel1.hidden = NO;
        cell.chooseBtn.hidden = NO;
        cell.chooseBtn1.hidden = NO;
        cell.edit_imageView.hidden = YES;
        if ([[DataModel object].userDetail[@"usex"] integerValue] == 1) {
            cell.chooseImageView.backgroundColor = [UIColor blueColor];
            cell.chooseImageView1.backgroundColor = [UIColor redColor];
            sex_Str = @"1";
        }
        if ([[DataModel object].userDetail[@"usex"] integerValue] == 2) {
            cell.chooseImageView1.backgroundColor = [UIColor blueColor];
            cell.chooseImageView.backgroundColor = [UIColor redColor];
            sex_Str = @"2";
        }
        [cell setDidSexSelectedCellBlock:^(EditDataCell *editCell) {

            editCell.chooseImageView.backgroundColor = [UIColor blueColor];
            editCell.chooseImageView1.backgroundColor = [UIColor redColor];
            sex_Str = @"1";
        }];
        [cell setDidOtherSelectedCellBlock:^(EditDataCell *other) {
            other.chooseImageView1.backgroundColor = [UIColor blueColor];
            other.chooseImageView.backgroundColor = [UIColor redColor];
            sex_Str = @"2";
        }];
    }
    if (indexPath.row == 2) {
        cell.editDataTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        cell.editDataTextField.placeholder = @"请输入年龄...";
        cell.editDataTextField.text = [DataModel object].userDetail[@"uage"];
    }
    if (indexPath.row == 3) {
        cell.editDataTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (IsNilString([DataModel object].userDetail[@"ucompellation"])) {
            cell.editDataTextField.placeholder = @"请输入真实姓名...";

        } else {
            cell.editDataTextField.text = [DataModel object].userDetail[@"ucompellation"];
        }
    }
    if (indexPath.row == 4) {
        cell.editDataTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
//        cell.editDataTextField.placeholder = @"请输入身份证号码...";
        if (IsNilString([DataModel object].userDetail[@"ucard"])) {
            cell.editDataTextField.placeholder = @"请输入身份证号码...";
        } else {
            cell.editDataTextField.text = [DataModel object].userDetail[@"ucard"];
        }
    }
    if (indexPath.row == 5) {
        cell.edit_imageView.hidden = YES;
        cell.lineView.hidden = YES;
        cell.editDataTextField.text = [DataModel object].userDetail[@"umobile"];
//        cell.editDataTextField.placeholder = @"请输入联系方式...";
        cell.editDataTextField.userInteractionEnabled = NO;
    }
    if (indexPath.row == 6) {
        cell.editDataTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (IsNilString([DataModel object].userDetail[@"uaddress"])) {
            cell.editDataTextField.placeholder = @"请输入详细地址...";
        } else {
            cell.editDataTextField.text = [DataModel object].userDetail[@"uaddress"];
        }
    }
    if (indexPath.row == 7) {
        cell.editDataTextField.hidden = YES;
        cell.lineView.hidden = YES;
        cell.chooseImageView.hidden = NO;
        cell.chooseImageView1.hidden = NO;
        cell.chooseLabel.hidden = NO;
        cell.chooseLabel1.hidden = NO;
        cell.chooseBtn.hidden = NO;
        cell.chooseBtn1.hidden = NO;
        cell.chooseLabel.text = @"是";
        cell.chooseLabel1.text = @"否";
        cell.edit_imageView.hidden = YES;
        
        if ([[DataModel object].userDetail[@"utype"] integerValue] == 0) {
            cell.chooseImageView1.backgroundColor = [UIColor blueColor];
            cell.chooseImageView.backgroundColor = [UIColor redColor];
            volunteers_Str = @"0";
        }
        if ([[DataModel object].userDetail[@"utype"] integerValue] == 1) {
            cell.chooseImageView1.backgroundColor = [UIColor redColor];
            cell.chooseImageView.backgroundColor = [UIColor blueColor];
            volunteers_Str = @"1";
        }
        [cell setDidSexSelectedCellBlock:^(EditDataCell *editCell) {
            editCell.chooseImageView.backgroundColor = [UIColor blueColor];
            editCell.chooseImageView1.backgroundColor = [UIColor redColor];
            volunteers_Str = @"1";
        }];
        [cell setDidOtherSelectedCellBlock:^(EditDataCell *other) {
            other.chooseImageView1.backgroundColor = [UIColor blueColor];
            other.chooseImageView.backgroundColor = [UIColor redColor];
            volunteers_Str = @"0";
        }];
    }
    
    [cell setDidEditTextfieldBlock:^(EditDataCell *editCell) {
       
        NSLog(@"输入的内容：%@",editCell.editDataTextField.text);
        NSIndexPath *indexPath = [tableView indexPathForCell:editCell];
        
        if (indexPath.row == 0) {
            
            [weakSelf.dataEdit_dic setObject:editCell.editDataTextField.text forKey:@"unickname"];
        }
        
        if (indexPath.row == 2) {
            
            [weakSelf.dataEdit_dic setObject:editCell.editDataTextField.text forKey:@"uage"];
            sss = editCell.editDataTextField.text;
        }
        if (indexPath.row == 3) {
            
            [weakSelf.dataEdit_dic setObject:editCell.editDataTextField.text forKey:@"ucompellation"];
        }
        if (indexPath.row == 4) {
            NSString *ucard = [NSString stringWithFormat:@"%@",editCell.editDataTextField.text];
            if (ucard.length == 16 || ucard.length == 18) {
                [weakSelf.dataEdit_dic setObject:editCell.editDataTextField.text forKey:@"ucard"];
            }else {
                [self waringAction:@"请输入正确的身份证号码"];
            }
                    }
        if (indexPath.row == 6) {
            
            [weakSelf.dataEdit_dic setObject:editCell.editDataTextField.text forKey:@"uaddress"];
        }
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

//头像上传按钮
- (void)headImageV_BtnAction {
    NSLog(@"点击添加头像");
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"上传头像" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //用户相册
        [self takePhotoPicker:UIImagePickerControllerSourceTypePhotoLibrary];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //拍照
        [self takePhotoPicker:UIImagePickerControllerSourceTypeCamera];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)takePhotoPicker:(UIImagePickerControllerSourceType)sourceType {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:picker animated:YES completion:nil];
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];
    _faceImage = image;
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //如果是拍照，保存到相册
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    //上传头像
    NSData *formData = UIImagePNGRepresentation(image);
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"user_token"];
    [dic setObject:token forKey:@"token"];
    
    [NetRequestClass NetUploadFilesPOSTWithRequestURL:headimg withParameter:dic data:formData compressData:imageData name:@"headeimg" fileName:@"file.png" mimeType:@"image/png" WithReturnValeuBlock:^(id returnValue) {
        
        NSLog(@"上传成功");
//        [SVProgressHUD showInfoStatus:@"头像上传成功" afterDelay:1.0];
        self.headImageView.image = _faceImage;
        
    } WithErrorCodeBlock:^(id errorCode) {
        
        NSLog(@"上传失败");
//        [SVProgressHUD showInfoStatus:@"头像上传失败" afterDelay:1.0];
        
    } WithFailureBlock:^{
        
        NSLog(@"上传失败");
//        [SVProgressHUD showInfoStatus:@"头像上传失败" afterDelay:1.0];
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//图片压缩到指定大小
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self.headImageView.image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

//上传资料 确定按钮
- (void)quedingBtnAction {
    
    NSLog(@"%@",self.dataEdit_dic);
    __weak typeof (self)weakSelf = self;
    
    [weakSelf.dataEdit_dic setObject:sex_Str forKey:@"usex"];
    
    [weakSelf.dataEdit_dic setObject:volunteers_Str forKey:@"utype"];
    
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"上传个人资料 = %@",returnValue);
        if ([returnValue[@"statu"] intValue] == 0) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            weakSelf.tabBarController.tabBar.hidden = NO;
        } else {
            [weakSelf waringAction:returnValue[@"result"]];
        }
        
    } WithErrorBlock:^(id errorCode) {
        
    }];
    [weakSelf.model userGetEdit_Userinfo:weakSelf.dataEdit_dic];
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
